import { Message, Loading, MessageBox } from 'element-ui'
import Fingerprint2 from 'fingerprintjs2'
// 导出Axios插件配置
export default ({ app, $axios, redirect, route, store, isDev, $cookies, router }) => {
  // 根据环境设置基础URL
  // 添加全局变量存储指纹
  let cachedFingerprint = null

  // 根据环境设置基础URL
  // $axios.defaults.baseURL = process.client
  //   ? process.env.apiURL
  //   : isDev
  //   ? process.env.apiURL
  //   : "http://127.0.0.1:9898";

  $axios.defaults.baseURL = process.env.apiURL

  // 设置axios默认配置
  $axios.defaults.withCredentials = true
  $axios.defaults.timeout = 30000

  // 定义默认请求配置
  const defaultConfig = {
    showSuccessMsg: false,
    showCheckMsg: true,
    showErrorMsg: false,
    showLoading: false,
    needToken: false,
    customCode: false,
    cutData: true
  }

  // Loading实例
  let loadingInstance = null

  // 支持的语言列表
  const locales = [
    '/ar',
    '/de',
    '/es',
    '/fr',
    '/hi',
    '/id',
    '/it',
    '/ja',
    '/ko',
    '/ms',
    '/my',
    '/nl',
    '/pt',
    '/ro',
    '/ru',
    '/th',
    '/tl',
    '/vi',
    '/zh-tw',
    '/zh'
  ]

  // 获取当前匹配的语言
  const matchedLocale = (locales.find(l => route.path.startsWith(l)) || '/en').replace('/', '')

  // 默认区域设置
  const DeSelect = {
    country_icon: '/flag/United%20States.png',
    country_code: 'US',
    currency_code: 'USD',
    language_code: matchedLocale
  }

  // 请求拦截
  $axios.onRequest(async config => {
    // 获取认证token
    const token = $cookies.get('token') || store.state.user.token

    // 获取用户区域设置
    const userSelect = $cookies.get('userSelect') || DeSelect
    userSelect.language_code = app.i18n.locale

    // 生成浏览器指纹
    const getFingerprint = () => {
      return new Promise(resolve => {
        if (process.client) {
          // 如果已缓存，直接使用缓存值
          if (cachedFingerprint) {
            resolve(cachedFingerprint)
            return
          }
          Fingerprint2.get(components => {
            const values = components.map(component => component.value)
            const fingerprint = Fingerprint2.x64hash128(values.join(''), 31)
            // 缓存指纹值
            cachedFingerprint = fingerprint
            resolve(fingerprint)
          })
        } else {
          resolve('server-side')
        }
      })
    }

    // 构建通用参数（包含token）
    const commonParams = {
      token,
      lang: userSelect.language_code,
      currency_code: userSelect.currency_code,
      deviceType: store.state.initData.deviceType,
      fp: await getFingerprint()
    }

    const queryString = new URLSearchParams(commonParams).toString()
    const separator = config.url.includes('?') ? '&' : '?'
    config.url = `${config.url}${separator}${queryString}`

    return config
  })
  // 响应拦截
  $axios.onResponse(res => {
    // 获取用户选择的语言和货币设置
    const userSelect = $cookies.get('userSelect') || DeSelect
    userSelect.language_code = app.i18n.locale
    const { language_code, currency_code } = userSelect

    // 合并配置
    const customConfig = { ...defaultConfig, ...(res.config.setConfig || {}) }

    // 处理加载状态
    if (defaultConfig.showLoading && loadingInstance) {
      loadingInstance.close()
    }

    // 统一处理登录跳转
    const goLoginConfirm = () => {
      store.commit('user/resetData')
      redirect({
        path: language_code !== 'en' ? `/${language_code}/login` : '/login'
      })
    }

    // 处理非成功状态码
    if (res.status !== 200) {
      return Promise.reject(res)
    }

    // 处理响应数据
    const { data, config } = res

    // 特殊接口处理
    if (config.url.includes('/api/user/callback')) {
      return handleCallbackResponse(data)
    }

    // 处理第三方注册
    if (isThirdPartyRegister(config)) {
      return handleThirdPartyRegister(data)
    }

    // 处理普通响应
    return handleNormalResponse(data, customConfig, goLoginConfirm)
  })

  // 处理回调响应
  const handleCallbackResponse = data => {
    if ([2404, 1].includes(data.code)) {
      return data
    }
    showErrorMessage(data.msg)
    return Promise.reject(data.msg)
  }

  // 判断是否为第三方注册
  const isThirdPartyRegister = config => {
    const requestData = config.data ? JSON.parse(config.data) : null
    return config.url.includes('/api/user/register') && requestData?.type === 'third'
  }

  // 处理第三方注册响应
  const handleThirdPartyRegister = data => {
    if ([2404, 2401, 1].includes(data.code)) {
      return data
    }
    showErrorMessage(data.msg)
    return Promise.reject(data.msg)
  }

  // 处理普通响应
  const handleNormalResponse = (data, customConfig, goLoginConfirm) => {
    if (data?.code === 1) {
      if (customConfig.showSuccessMsg) {
        showSuccessMessage(data.msg)
      }
      return customConfig.cutData ? data.data : data
    }

    if (data.code === 401) {
      goLoginConfirm()
      return
    }

    if (customConfig.showCheckMsg) {
      showErrorMessage(data.msg)
    }
    return Promise.reject(data)
  }

  // 显示错误消息
  const showErrorMessage = message => {
    Message({
      showClose: true,
      message,
      type: 'error'
    })
  }

  // 显示成功消息
  const showSuccessMessage = message => {
    Message({
      showClose: true,
      message,
      type: 'success'
    })
  }
  // 错误处理
  $axios.onError(error => {
    const customConfig = { ...defaultConfig, ...error.config?.setConfig }

    // 清除加载状态
    if (customConfig.showLoading && loadingInstance) {
      loadingInstance.close()
    }

    const status = error.response?.status
    const errorMessage = error.response?.data?.msg || 'Request failed'

    // 处理401未登录状态
    if (status === 401) {
      store.commit('user/resetData')

      if (process.client) {
        const currentUrl = encodeURIComponent(window.location.href)
        return app.router.push({
          path: app.localePath(`/login?redirect=${currentUrl}`)
        })
      }

      return redirect(app.localePath('/login'))
    }

    // 显示错误提示
    if (status !== 401 && customConfig.showErrorMsg) {
      Message({
        showClose: true,
        message: errorMessage,
        type: 'error',
        duration: 3000
      })
    }

    return Promise.reject(error)
  })
}
